#include <stdio.h>
#include <stdbool.h>
#include <util/atomic.h>
#include "timer.h"

volatile uint16_t TickCounter;

void ResetDelay(uint16_t* const DelayCounter)
{
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
        *DelayCounter = TickCounter;
    }
}


bool HasDelayElapsed(const uint16_t Delay, uint16_t* const DelayCounter, bool Reset)
{
    uint16_t CurrentTickValue_LCL;
    uint16_t DelayCounter_LCL;

    ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
    {
        CurrentTickValue_LCL = TickCounter;
    }

    DelayCounter_LCL = *DelayCounter;

    if (CurrentTickValue_LCL >= DelayCounter_LCL)
    {
        if ((CurrentTickValue_LCL - DelayCounter_LCL) >= Delay)
        {
            if (Reset) *DelayCounter = CurrentTickValue_LCL;
            return true;
        }
    }
    else
    {
        if (((0xFFFF - DelayCounter_LCL) + CurrentTickValue_LCL) >= Delay)
        {
            if (Reset) *DelayCounter = CurrentTickValue_LCL;
            return true;
        }
    }

    return false;
}
